<?php

/**
 * @author hungnq@younetco.com
 */
class Core_Model_Entry extends YouNet_Db_Table_Row implements Core_Model_IEntry
{
	public $fullname;
	public $link;
	
	public function vote($id_user)
	{
		$votes_db = new Core_Model_DbTable_Votes();
		$ns = Zend_Registry::get('session');
		$id_ref_user	= 0;
		$inc_share		= false;
		if(!empty($ns->id_user_ref) && ($ns->id_entry == $this->id))
		{
			$id_ref_user = $ns->id_user_ref;
			$inc_share	 = true;
			unset($ns->id_user_ref);
			unset($ns->id_entry);
		}

		$data = array(
			'id_entry'		=> $this->id,
			'id_user'		=> $id_user,
			'time_voted'	=> time(),
			'ip'			=> $_SERVER['REMOTE_ADDR'],
			'id_ref_user'	=> $id_ref_user
		);
		$returnValue = $votes_db->insert($data);
		
		$entries_db = new Core_Model_DbTable_Entries();
		$entry = $entries_db->findOne($this->id); 
		
		$entry->votes+=1;
        $this->votes = $entry->votes;
		//Clear is_vote
		$key		= Core_Cache_IKeys::MEMCACHE_USER_ENTRY_IS_VOTED.$id_user.'_'.$this->id;
		YouNet_Util::getMemCache()->save(1,$key);
		//clear allow vote
		$key	= Core_Cache_IKeys::MEMCACHE_USER_ENTRY_ALLOW_VOTE.$id_user.'_'.$this->id;
		YouNet_Util::getMemCache()->save(0,$key);
		if($inc_share)
		{
			$entry->shares+=1;
            $this->shares = $entry->shares;
		}
		$entry->save();
		return ($returnValue);
	}
	
	public function updateView($id_user= 1, $id_ref_user = 1)
	{
		$ns = Zend_Registry::get('session');
		if(!isset($ns->entry_{$this->id}))
		{
			$ns->entry_{$this->id} = 1;
			$entry_views_db = Core_Model_DbTable_EntryViews::getInstance();

			$data = array(
				'id_entry' => $this->id,
				'id_user' => $id_user,
				'time_viewed' => time(),
				'ip' => $_SERVER['REMOTE_ADDR'],
				'id_ref_user' => $id_ref_user
			);

			$entry_views_db->insert($data);

			
			$entries_db = new Core_Model_DbTable_Entries();
			$entries_db->update(
				array(
					'views'		=> new Zend_Db_Expr('views + 1')
				),
				array(
					'id = ?'	=> $this->id 
				)
			);
			$this->views += 1;
			YouNet_Util::getMemCache()->save(
				$this->toArray(),
				Core_Cache_IKeys::MEMCACHE_MODEL_ENTRY.$this->id
			);
		}		
	}
	
	public function getHref()
	{
		return '/contest/entry/view/id_entry/' . $this->id;
	}
	
	public function getHrefWithIDSocial()
	{
		$social = YouNet_Api::getInstance()->getSocialPlugin();
		return $this->getHref() . '/id_social_ref/' . $social->getIdSocial();
	}
	
	public function getCommentHref()
	{
		return 'http://' . $_SERVER['HTTP_HOST'] . $this->getHref();
	}
	
	public function getHrefWithIDUser($id_user_ref)
	{
		$social = YouNet_Api::getInstance()->getSocialPlugin();
        $href = $this->getHref() . '/from_page/' . $social->getIdPage();
		$href = $href  . '/id_user_ref/' . ($id_user_ref?$id_user_ref:ID_USER_CHEAT_FOR_COUNT_SHARE);
		
		return $social->getShareUrl($href);
	}
	
	public function getFanpage()
	{
		$pagesTable = Core_Model_DbTable_Pages::getInstance();
		$fanpage	= $pagesTable->getFanpageByIdContest($this->id_contest);
		return $fanpage;
	}
	
	public function getShortTitle()
	{
		if(strlen($this->title) > 20)
		{
			return substr($this->title, 0, 17) . '...';
		}
		else
		{
			return $this->title;
		}
	}
	
	public function getSubmitDate($format = DATE_FORMAT_HUMAN_DISPLAY)
	{
		return date($format,$this->time_uploaded);
	}
	
	/**
	 * @todo Need to cache this function
	 * @return array 
	 */
	public function getEntryFieldInfoList()
	{
		$select = $this->select()
			->setIntegrityCheck(false)
			->from(array('e' => Core_Model_DbTable_Entries::TABLE_NAME),'e.*')
			->join(
				array('i' => Core_Model_DbTable_CandidateInfo::TABLE_NAME),
				'e.id_user = i.id_user',
				array('i.*')
			)
			->join(
				array('f' => Core_Model_DbTable_EntryFields::TABLE_NAME),
				'f.id = i.id_entry_field',
				array('f.*')
			)
			->where('e.id = ?',$this->id);			
		return $select->query()->fetchAll();
	}
	
	/**
	 * @deprecated by Tran Phong Phu
	 * @uses self::getCandidateName()
	 * @return String 
	 */
	public function getRegistrantName()
	{
		trigger_error('The method '.__METHOD__.' was deprecated as of '
                    . 'version 1.0, and may be removed. You\'re encouraged '
                    . 'to use getCandidateName() instead.');
		$format			= '%s %s %s';
		$firstname		= '';
		$middlename		= '';
		$lastname		= '';
		$fieldInfoList = $this->getEntryFieldInfoList();
		foreach($fieldInfoList as $fieldInfo)
		{
			if( $fieldInfo['type'] == Core_Model_IEntryFields::INDEX_FIRST_NAME)
			{
				$firstname = $fieldInfo['value'];
			}
			if( $fieldInfo['type'] == Core_Model_IEntryFields::INDEX_MIDDLE_NAME)
			{
				$middlename = $fieldInfo['value'];
			}
			if( $fieldInfo['type'] == Core_Model_IEntryFields::INDEX_LAST_NAME)
			{
				$lastname = $fieldInfo['value'];
			}
		}
		$fullname = sprintf($format, $firstname, $middlename, $lastname);
		str_replace('/\s+/', ' ', $fullname);
		return $fullname;
	}
	
	/**
	 * Get candidate info as $values[key] = value
	 * @return array $values
	 */
	public function getCandidateInfo()
	{
		$values = array();
		
		$candidateInfoTable		=	new Core_Model_DbTable_CandidateInfo();
		$candidateInfoRowSet	=	$candidateInfoTable->getCandidateInfo($this->id_user, $this->id_contest);
		$fieldTypes				=	Core_Model_DbTable_EntryFields::getListFieldTypes();
		$countryModel			=	Core_Model_DbTable_Countries::getInstance();
		$gender					=	Tab_Form_Entry::getGender();
		
		foreach($candidateInfoRowSet as $row)
		{
			switch($row->label)
			{
				case Core_Model_IEntryFields::FIELD_GENDER:
					if($row->value !=-1)
					{
						$values[$row->label] = $gender[$row->value];
					}
					else
					{
						$values[$row->label] = -1;
					}
					break;
				case Core_Model_IEntryFields::FIELD_COUNTRY:
					if($row->value !=-1)
					{
						$values[$row->label] = $countryModel->findOne($row->value)->country;
					}
					else
					{
						$values[$row->label] = -1;
					}
					break;
                case Core_Model_IEntryFields::FIELD_DATE_OF_BIRTH:
                    $values[$row->label] = date('d/m/Y', strtotime($row->value));
                    break;
				default:
					$values[$row->label] = $row->value;
					break;
			}
		}
		return $values;
	}
	
	public function getEmbeddedCode()
	{
		return Core_Video::factory($this->image)->getEmbededdCode();
	}
	
	public function getSubmissionImageUrl()
	{
		$value = '';
		if( APP_INSTANCE == APP_INSTANCE_IMAGE )
		{
			$value = YouNet_Util::createFullUrl(STATIC_URL.'/media/image/'.$this->image);
		}
		else
		{
			$value = $this->image;
		}
		return $value;
	}
    
    public function getImageUrl()
    {
        return STATIC_URL . '/media/image/' . $this->image;
    }
	
	public function getThumbnailImageUrl()
	{
		$value = '';
		if( APP_INSTANCE == APP_INSTANCE_IMAGE)
		{
			$value = STATIC_URL.'/media/image/thumbnail/'.$this->image;
		}
		else
		{
			$value = Core_Video::factory($this->image)->getThumbnailUrl();
		}
		return $value;
	}
	
	public function getShareUrl($params = array())
	{
		$social = YouNet_Api::getInstance()->getSocialPlugin();
		return $social->getShareUrl(array_merge(array(
			'module'		=> 'contest',
			'controller'	=> 'entry',
			'action'		=> 'view',
			'id_entry'		=> $this->id,
			'from_page'		=> $social->getIdPage()
		),$params),'default',true);
	}
    
    public function getShareUrlSocialNetworks($params = array(), $is_facebook = true) {
        $social = YouNet_Api::getInstance()->getSocialPlugin();
        $params = array_merge(array(
			'module'		=> 'contest',
			'controller'	=> 'entry',
			'action'		=> 'view',
			'id_entry'		=> $this->id,
			'from_page'		=> $social->getIdPage()),$params);
        if( $is_facebook )
        {
            return $social->getShareUrl($params,'default',true);
        }
        $viewInstace	= Zend_Layout::getMvcInstance()->getView();
        return $viewInstace->serverUrl($viewInstace->url($params, 'default'));
    }
    
	public function getCanonicalUrl()
	{
		return $this->getShareUrl();
	}
	
	public function getCommentUrl()
	{
		return $this->getShareUrl();
	}


	public function getStatusLabel()
	{
		return Core_Model_DbTable_Entries::getStatusLabelByInt($this->status);
	}
	/**
	 *
	 * @return Core_Model_User
	 */
	public function getUser()
	{
		$userTable	= new Core_Model_DbTable_Users();
		$userRow	= $userTable->findOne($this->id_user);
		return $userRow;
	}
	
	/**
	 *
	 * @return string
	 */
	public function getCandidateName()
	{
		$fullname = $this->getFullname();
		if( empty($fullname) )
		{
			$candidateInfoTable = Core_Model_DbTable_CandidateInfo::getInstance();
			$fullname 			= $candidateInfoTable->getCandidateName($this->id_user, $this->id_contest);
		}
		return $fullname;
	}
	
	public function getFanPageEntryLink()
	{
		return YouNet_Api::getInstance()->getSocialPlugin()->pageUrl(array('target' => 'image', 'id_entry' => $this->id));
	}
	
	/**
	 *
	 * @return Core_Model_Contest
	 */
	public function getContest()
	{
		$contestTable	= new Core_Model_DbTable_Contests();
		$contestRow		= $contestTable->findOne($this->id_contest);
		return $contestRow;
	}

	public function getShareTitle()
	{
		$format = '"%s" contest : %s';
		return sprintf($format,	$this->getContest()->title, $this->title);
	}
	/**
	 *
	 * @return Integer
	 */
	public function getUserScore()
	{
		return $this->user_score;
	}
	
	public function getTotalScore1()
	{
		return $this->_getTotal(1);
	}
	public function getTotalScore2()
	{
		return $this->_getTotal(2);
	}
	
	public function getScore1()
	{
		return $this->_getScore(1);
	}
	
	public function getScore2()
	{
		return $this->_getScore(2);
	}
	
	private function _getScore($index)
	{
		$column = "score{$index}";
		return isset($this->_data[$column])?$this->$column:'n/a';
	}
	private function _getTotal($index)
	{
		$column = "total{$index}";
		return round($this->$column,2);
	}
	
	/**
	* @deprecated by phutp
	* @see Core_Model_Contest::getArrIdPages
	*/
	public function getPublishedPageID()
	{
		$pages		= array();
		$pagesModel = Core_Model_DbTable_Pages::getInstance();
		$pages		= $pagesModel->getArrayPagesID($this->id_contest);
		
		return $pages;
	}
	
	public function save()
	{
		YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_MODEL_ENTRY.$this->id);
		YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_CONTEST_CONTROL.$this->id_contest);
        YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_INDEX_ID_ENTRY_APPROVE.$this->id_contest);
		return parent::save();
	}
	
	public function getFullname()
	{
		if( isset($this->_data['fullname']) )
		{
			return $this->_data['fullname'];
		}
		return $this->fullname;
	}
	
	public function getLink()
	{
		if( isset($this->_data['link']) )
		{
			return $this->_data['link'];
		}
		return $this->link;
	}
	
	public function isApproved()
	{
		return $this->status == self::STATUS_APPROVED;
	}
	
	/**
	 * @return string
	 * @param string $format
	 */
    public  function _processing_header($arr_header,&$active_sheet)
    {
        $row = 1;
        $styleArray = array(
            'font' => array(
                'bold' => true,
            )
        );

        $col = 0 ;
        foreach ( $arr_header as $field )
        { 
            $active_sheet->setCellValueByColumnAndRow($col, $row, $field)->getStyleByColumnAndRow($col,$row)->applyFromArray($styleArray);
            $col =  $col + 1;
        }
        
    }
    public function _processing_data($arrData,$row,&$active_sheet)
    {
        $col = 0 ;
        foreach ($arrData as $cell_val)
        {
           $active_sheet->setCellValueByColumnAndRow($col, $row, $cell_val);
           $col = $col + 1;
        }
    }
	public function exportVoters(&$active_sheet,$contest)
	{
        $time_zone	= (int)$contest->time_zone * 3600;
         $this->_processing_header(array(
            YouNet_Util::translate('EXPORT_HEADER_ENTRY_ID'),
            YouNet_Util::translate('EXPORT_HEADER_VOTED_TIME'),
            YouNet_Util::translate('EXPORT_HEADER_FACEBOOK_NAME'),
            YouNet_Util::translate('EXPORT_HEADER_EMAIL'),
            YouNet_Util::translate('EXPORT_HEADER_PROFILE'),
            YouNet_Util::translate('EXPORT_HEADER_GENDER')
            ),$active_sheet);
        
		$entryVoteTbl = new Core_Model_DbTable_EntryVotes();
		$select = $entryVoteTbl->select()->setIntegrityCheck(false);
		$select->from(array('e' => Core_Model_DbTable_EntryVotes::TABLE_NAME), array('e.time_voted','e.ip','e.id_ref_user'));
		$select->joinInner(array('u' => Core_Model_DbTable_Users::TABLE_NAME), 'u.id = e.id_user' , array('u.*'));
		$select->where('e.id_entry = ?', $this->id);
		$select->order('e.time_voted DESC');
		$stm = $select->query();
		$result = array();
		if( $stm->execute() )
		{
            $i_row  = 2;
			
            while($row = $stm->fetch())
            {
                  $this->_processing_data(array(
                            $this->id,
                            date('M d, Y H:i:s',$row['time_voted']+$time_zone),
                            $row['name'] ,
                            $row['email'],
                            $row['link'],
                            $row['gender']
                        ),$i_row,$active_sheet);

                 $i_row = $i_row  +1;
            }
		}
		
	}
}
